﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Refit;

using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;


using MyETFData.Model;
using MyETFData.Service;


namespace XueQiuReader
{
    internal class Program
    {


        static IETFService _ETFService = RestService.For<IETFService>(ConfigurationManager.AppSettings["Postgrest:Server"]);


        static ChromeOptions opt = new ChromeOptions();
        static ChromeDriver driver = new ChromeDriver(ConfigurationManager.AppSettings["ChromeDriver:Path"], opt);


        static void Main(string[] args)
        {

            List<ETFInfo> etfDataList = _ETFService.GetETFInfosAsync().Result;

            foreach(var etf in etfDataList)
            {
                GetData(etf.etf_code);

                Thread.Sleep(5678);
            }

            driver.Close();
        }



        static void GetData(string code)
        {
            Console.WriteLine(code);



            driver.Navigate().GoToUrl($"https://xueqiu.com/S/{code}");


            // 当前价的 div.
            var currentPriceDiv = driver.FindElementByClassName("stock-current");

            string priceText = currentPriceDiv.Text;
            priceText = priceText.Replace("¥", "");




            // 日期.
            var dateDiv = driver.FindElementByClassName("quote-market-status");

            string dateText = dateDiv.Text;

            dateText = dateText.Replace("休市", "");
            dateText = dateText.Replace("15:00:00", "");
            dateText = dateText.Replace("北京时间", "");
            dateText = dateText.Trim();


            // 价格详情的 Table.
            var tab = driver.FindElementByClassName("quote-info");

            string tabText = tab.Text;
/*
最高：3.950 今开：3.931 涨停：4.323 成交量：26.08万手
最低：3.852 昨收：3.930 跌停：3.537 成交额：1.02亿
换手：--市价：3.863 单位净值：3.920 基金份额：55.52亿
振幅：2.49 % 溢价率：-1.45 % 累计净值：4.194 资产净值：214.46亿
成立日：2006 - 04 - 13 净值日期：2022 - 01 - 27 到期日：--货币单位：CNY
*/

            string highStr = GetValue(tabText, "最高：", "今开");
            string openStr = GetValue(tabText, "今开：", "涨停");
            string lowStr = GetValue(tabText, "最低：", "昨收");
            string volumeStr = GetValue(tabText, "成交额：", "换手");

            

            DayLineRequest request = new DayLineRequest();
            request.p_code = code;
            request.p_date = $"{DateTime.Today.Year}-{dateText}";

            request.p_open = Convert.ToDecimal(openStr.Trim());
            request.p_close = Convert.ToDecimal(priceText);

            request.p_highest = Convert.ToDecimal(highStr.Trim());
            request.p_lowest = Convert.ToDecimal(lowStr.Trim());


            volumeStr = volumeStr.Trim();
            if (volumeStr.EndsWith("亿"))
            {
                volumeStr = volumeStr.Replace("亿", "");
                request.p_volume = Convert.ToDecimal(volumeStr) * 100000000;
            } 
            else if (volumeStr.EndsWith("万"))
            {
                volumeStr = volumeStr.Replace("万", "");
                request.p_volume = Convert.ToDecimal(volumeStr) * 10000;
            }



            ServiceResult result = _ETFService.InsertDayLineAsync(request).Result;
            Console.WriteLine($"Finish! Result = {result}");
            

        }




        /// <summary>
        /// 获取数值.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="title"></param>
        /// <param name="nextTitle"></param>
        /// <returns></returns>
        private static string GetValue(string source, string title, string nextTitle)
        {
            int startIndex = source.IndexOf(title);
            int nextIndex = source.IndexOf(nextTitle);

            string result = source.Substring(startIndex + title.Length, 
                nextIndex - (startIndex + title.Length));

            return result;
        }



    }
}
